package com.netdisk.controller;

import com.netdisk.dto.FileDTO;
import com.netdisk.dto.ShareDTO;
import com.netdisk.service.FileService;
import com.netdisk.service.ShareService;
import com.netdisk.service.UserActivityService;
import com.netdisk.vo.PageResult;
import com.netdisk.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 分享控制器
 */
@Api(tags = "文件分享")
@RestController
@RequestMapping("/share")
public class ShareController {

    @Autowired
    private ShareService shareService;

    @Autowired
    private FileService fileService;
    
    @Autowired
    private UserActivityService userActivityService;

    @ApiOperation("创建分享")
    @PostMapping("/create")
    public Result<ShareDTO> createShare(
            @ApiParam(value = "文件ID", required = true) @RequestParam("fileId") Integer fileId,
            @ApiParam(value = "用户ID", required = true) @RequestParam("userId") Integer userId,
            HttpServletRequest request) {
        
        // 获取文件信息，用于记录活动
        FileDTO fileDTO = fileService.getFileInfo(fileId, userId);
        
        ShareDTO shareDTO = shareService.createShare(fileId, userId);
        
        // 记录分享文件活动
        try {
            userActivityService.recordActivity(
                userId, 
                fileId, 
                fileDTO.getName(), 
                "share", 
                "分享了文件 \"" + fileDTO.getName() + "\"",
                request.getRemoteAddr(),
                request.getHeader("User-Agent")
            );
        } catch (Exception e) {
            // 记录活动失败，但不影响分享功能
            System.err.println("Failed to record activity: " + e.getMessage());
        }
        
        return Result.success("分享成功", shareDTO);
    }

    @ApiOperation("获取分享信息")
    @GetMapping("/info/{shareId}")
    public Result<ShareDTO> getShareInfo(@PathVariable("shareId") String shareId) {
        ShareDTO shareDTO = shareService.getShareInfo(shareId);
        return Result.success(shareDTO);
    }

    @ApiOperation("获取用户分享列表")
    @GetMapping("/list")
    public Result<PageResult<ShareDTO>> listUserShares(
            @ApiParam(value = "用户ID", required = true) @RequestParam("userId") Integer userId,
            @ApiParam(value = "页码", defaultValue = "1") @RequestParam(value = "page", defaultValue = "1") Integer page,
            @ApiParam(value = "每页大小", defaultValue = "10") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @ApiParam(value = "搜索关键词", required = false) @RequestParam(value = "query", required = false, defaultValue = "") String query) {
        
        try {
            PageResult<ShareDTO> pageResult = shareService.listUserShares(userId, page, pageSize, query);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取分享列表失败：" + e.getMessage());
        }
    }

    @ApiOperation("取消分享")
    @DeleteMapping("/cancel")
    public Result<Void> cancelShare(
            @ApiParam(value = "分享ID", required = true) @RequestParam("shareId") String shareId,
            @ApiParam(value = "用户ID", required = true) @RequestParam("userId") Integer userId,
            HttpServletRequest request) {
        
        try {
            System.out.println("接收到取消分享请求: shareId=" + shareId + ", userId=" + userId);
            
            // 获取分享信息，用于记录活动
            ShareDTO shareDTO = null;
            try {
                shareDTO = shareService.getShareInfo(shareId);
                System.out.println("找到分享信息: " + shareDTO);
            } catch (Exception e) {
                System.err.println("获取分享信息失败: " + e.getMessage());
                return Result.error("找不到分享信息: " + e.getMessage());
            }
            
            FileDTO fileDTO = null;
            if (shareDTO != null && shareDTO.getFile() != null) {
                fileDTO = shareDTO.getFile();
                System.out.println("关联文件信息: " + fileDTO.getName());
                
                try {
                    boolean result = shareService.cancelShare(shareId, userId);
                    System.out.println("取消分享结果: " + result);
                    
                    if (result) {
                        // 记录取消分享活动
                        try {
                            userActivityService.recordActivity(
                                userId, 
                                fileDTO.getId(), 
                                fileDTO.getName(), 
                                "unshare", 
                                "取消了文件 \"" + fileDTO.getName() + "\" 的分享",
                                request.getRemoteAddr(),
                                request.getHeader("User-Agent")
                            );
                        } catch (Exception e) {
                            // 记录活动失败，但不影响取消分享功能
                            System.err.println("Failed to record activity: " + e.getMessage());
                        }
                        
                        return Result.success("取消分享成功", null);
                    } else {
                        return Result.error("取消分享失败");
                    }
                } catch (Exception e) {
                    System.err.println("取消分享操作失败: " + e.getMessage());
                    e.printStackTrace();
                    return Result.error("取消分享失败: " + e.getMessage());
                }
            } else {
                System.err.println("无法获取文件信息");
                return Result.error("无法获取文件信息");
            }
        } catch (Exception e) {
            System.err.println("取消分享过程中发生异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("取消分享失败: " + e.getMessage());
        }
    }
}